package com.zhl.service_.impl;

import com.zhl.dao_.UserMapper;
import com.zhl.entity.User;
import com.zhl.service_.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Administrator on 2018/11/6.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        return userMapper.login(username,password);
    }

    @Override
    public User queryUserByid(int id) {
        return userMapper.queryUserByid(id);
    }

    @Override
    public User queryUserByUsername(String username) {
        return userMapper.queryUserByUsername(username);
    }

    @Override
    public List<User> userList() {
        return userMapper.userList();
    }

    @Override
    public int addUserRole(int id, String rids) {

        if (StringUtils.isNotEmpty(rids)) {

            //mybatis没有类似hibernate的自动维护中间表,需要先删除,免得重复
            userMapper.deleteUserRoleById(id);

            String[] split = rids.split(",");
            for (String fid : split) {
                if (!fid.equals("all")) {
                    userMapper.addUserRole(id,fid);
                }
            }

        }

        return 1;
    }

    @Override
    public int register(User user) {

        User checkUser = queryUserByUsername(user.getUsername());
        if (checkUser != null) {
            return 0;
        }
        userMapper.addUser(user);
        int id = user.getId();//获取添加对象的主键

        //赋予普通用户的角色
        int i = addUserRole(id, "1");

        return i;
    }
}
